import {
  Injectable,
  UnauthorizedException,
  BadRequestException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { UserService } from 'src/module/user/user.service';
import { pswToMd5 } from 'src/utils/md5';

@Injectable()
export class AuthService {
  constructor(
    private readonly userService: UserService,
    private readonly jwtService: JwtService,
  ) {}

  async validateUser(username: string, password: string) {
    const user = await this.userService.findOneByName(username);
    // console.log('auth服务层：登录用户：', user);
    console.log(user && user.password === pswToMd5(password));
    if (user && user.password === pswToMd5(password)) {
      return user;
    }
    throw new BadRequestException({ msg: '账号或密码错误！', success: 0 });
  }

  login(userInfo: any) {
    console.log('登录 === > ', userInfo);
    const payload = { username: userInfo.username, roles: userInfo.roles };
    // 颁发token
    return { access_token: this.jwtService.sign(payload) };
  }

  // 手动检验token
  verifyToken(token: string) {
    if (!token) {
      throw new UnauthorizedException({ msg: '请先登录~', success: 0 });
    }
    const userInfo = this.jwtService.verify(token.replace('Bearer ', ''));
    return userInfo;
  }
}
